<template>
  <div class="czr-form">
    <el-form ref="ref_czrForm" :label-width="labelWidth" v-bind="$attrs" @submit.native.prevent>
      <el-row style="display:flex; flex-wrap: wrap">
        <slot/>
      </el-row>
    </el-form>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: 'CzrForm',
});
import {
  ref,
  reactive,
  watch,
  provide
} from 'vue'
const emit = defineEmits(['handleEnter'])
const props = defineProps({
  labelWidth: {default: 'auto'},
  elementLoadingBackground: {default: null},
  formView: {default: false}
})
const state = reactive({
  formChildrenMap: new Map()
})
const ref_czrForm: any = ref(null)
provide('element-loading-background', props.elementLoadingBackground)
provide('czr-form-children-map', state.formChildrenMap)
let _formView: any = ref(props.formView)
watch(() => props.formView, (n) => {
  _formView.value = n
})
provide('form-view', _formView)
const submit = () => {
  return new Promise((resolve, reject) => {
    const nodes: any = [];
    state.formChildrenMap.forEach((v: any, k: string) => {
      const errorMessage = v.handleValidate()
      if (errorMessage) {
        nodes.push({
          uuid: k,
          node: v,
          message: errorMessage
        });
      }
    })
    if (nodes.length > 0) {
      reject(nodes);
    } else {
      resolve(null);
    }
  });
}
const handleEnter = () => {
  emit('handleEnter')
}
provide('handle-enter', handleEnter)
const reset = () => {
  state.formChildrenMap.forEach((v: any, k: string) => {
    v.reset()
  })
}
defineExpose({
  reset,
  submit,
})
</script>

<style scoped lang="scss">
</style>
